package com.wn.login.service

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.wn.common.constant.LOGIN_SERVICE_LOGIN
import com.wn.common.service.ILoginService
import com.wn.login.LoginActivity
import com.wn.login.view.PrivacyPolicyActivity
import com.wn.network.api.ApiInterface
import com.wn.network.utils.ApiManager
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @Author: wn
 * @Date: 2025/6/25 15:58
 * @Description: ILoginService 接口的具体实现
 */
@Route(path = LOGIN_SERVICE_LOGIN)
class LoginService : ILoginService {

  private val api: ApiInterface by lazy {
    ApiManager.create(ApiInterface::class.java)
  }

  /**
   * 跳转登录页
   * @param context Context
   */
  override fun toLogin(context: Context) {
    LoginActivity.toLogin(context)
  }

  /**
   * 跳转隐私协议
   * @param context Context
   */
  override fun readPolicy(context: Context) {
    PrivacyPolicyActivity.start(context)
  }

  /**
   * 登出
   * @param context Context
   * @param lifecycleOwner LifecycleOwner?
   * @param observer Observer<Boolean>
   */
  @OptIn(DelicateCoroutinesApi::class)
  override fun logout(
    context: Context,
    lifecycleOwner: LifecycleOwner?,
    observer: Observer<Boolean>,
  ) {
    val scope = lifecycleOwner?.lifecycleScope ?: GlobalScope
    scope.launch {
      val response = api.logout()
      if (response?.isFailed() == true) {
        ToastUtils.showShort(response.errorMsg)
        return@launch
      }
      // true 表示  失败
      observer.onChanged(response?.isFailed() == true)
      // 跳转登陆页
      toLogin(context)
    }
  }

  /**
   * Do your init work in this method, it well be call when processor has been load.
   * @param context ctx
   */
  override fun init(context: Context?) {
  }
}